//
//  SearchViewController.m
//  LoveHealth
//
//  Created by 枫哥 on 14-9-24.
//  Copyright (c) 2014年 lanou. All rights reserved.
//

#import "SearchViewController.h"
#import "ChineseInclude.h"
#import "PushView.h"


#import "SearchResultModel.h"

#import "SearchTableViewCell.h"

#import "HealthNewsDetailViewController.h"
#import "HealthFoodDetailViewController.h"

#import "HealthKnowledgeDetailViewController.h"

#import "NetHelper.h"
#import "KGStatusBar.h"
@interface SearchViewController ()

@property (nonatomic,retain) NSMutableArray *dataArray;
@property (nonatomic,retain) NSMutableArray *searchResults;
@property(nonatomic,retain)UITableView * tableView;
@property (nonatomic,retain)NSString * urlString;
@end

@implementation SearchViewController

- (void)dealloc
{
    self.dataArray = nil;
    self.searchResults = nil;
    self.tableView = nil;
    self.urlString = nil;
    [super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"搜索";
    self.view.backgroundColor = [UIColor cyanColor];
    
    _tableView = [[UITableView alloc]initWithFrame:self.view.frame];
    [self.view addSubview:_tableView];
    
    mySearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
    mySearchBar.delegate = self;
    [mySearchBar setPlaceholder:@"请输入关键词"];
    
    
    searchDisplayController = [[UISearchDisplayController alloc]initWithSearchBar:mySearchBar contentsController:self];
    searchDisplayController.active = NO;
    searchDisplayController.searchResultsDataSource = self;
    searchDisplayController.searchResultsDelegate = self;
  

    self.tableView.dataSource = self;
    self.tableView.delegate = self;
	self.tableView.tableHeaderView = mySearchBar;
  
    NSLog(@"%ld",self.type);
    
    
    switch (self.type) {
        case foodType:
            self.urlString = APIHealthFoodSearch;
            break;
        case newsType:
            self.urlString = APIHealthNewsSearch;
            break;
        case knowledgeType:
            self.urlString = APIHealthKnowledgeSearch;
            break;
        default:
            break;
    }
}

#pragma UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return _searchResults.count;
    }
    else {
        return _dataArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    SearchTableViewCell *cell = (SearchTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[SearchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    if (tableView == self.searchDisplayController.searchResultsTableView) {
    
        SearchResultModel * searchResult =  _searchResults[indexPath.row];
        [cell.searchWebView loadHTMLString:searchResult.title baseURL:nil ];
    }
    else {
        SearchResultModel * searchResult = _dataArray[indexPath.row];
        [cell.searchWebView loadHTMLString:searchResult.title baseURL:nil ];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

     SearchResultModel * searchResult =  _searchResults[indexPath.row];
    
    switch (self.type) {
        case newsType:{
            HealthNewsDetailViewController * newsDVC = [[HealthNewsDetailViewController alloc]init];
            newsDVC.searchResult = searchResult;
            [self.navigationController pushViewController:newsDVC animated:YES];
            [newsDVC release];
            
        }
            break;
        case knowledgeType:{
            HealthKnowledgeDetailViewController * knowledgeDVC = [[HealthKnowledgeDetailViewController alloc]init];
            knowledgeDVC.searchResult = searchResult;
            [self.navigationController pushViewController:knowledgeDVC animated:YES];
            [knowledgeDVC release];
            
        }
            break;
        case foodType:{
            HealthFoodDetailViewController * foodDVC = [[HealthFoodDetailViewController alloc]init];
            foodDVC.searchResult = searchResult;
            [self.navigationController pushViewController:foodDVC animated:YES];
            [foodDVC release];
        }
            break;
        default:
            break;
    }
}

#pragma UISearchDisplayDelegate


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

    
    _searchResults = [[NSMutableArray alloc]init];
    
    
    NSLog(@"=====%@",searchText);

    
    
    /*
    if (mySearchBar.text.length>0&&![ChineseInclude isIncludeChineseInString:mySearchBar.text]) {
        for (int i=0; i<dataArray.count; i++) {
            if ([ChineseInclude isIncludeChineseInString:dataArray[i]]) {
                NSString *tempPinYinStr = [PinYinForObjc chineseConvertToPinYin:dataArray[i]];
                NSRange titleResult=[tempPinYinStr rangeOfString:mySearchBar.text options:NSCaseInsensitiveSearch];
                if (titleResult.length>0) {
                    [searchResults addObject:dataArray[i]];
                }
                NSString *tempPinYinHeadStr = [PinYinForObjc chineseConvertToPinYinHead:dataArray[i]];
                NSRange titleHeadResult=[tempPinYinHeadStr rangeOfString:mySearchBar.text options:NSCaseInsensitiveSearch];
                if (titleHeadResult.length>0) {
                    [searchResults addObject:dataArray[i]];
                }
            }
            else {
                NSRange titleResult=[dataArray[i] rangeOfString:mySearchBar.text options:NSCaseInsensitiveSearch];
                if (titleResult.length>0) {
                    [searchResults addObject:dataArray[i]];
                }
            }
        }
    } else if (mySearchBar.text.length>0&&[ChineseInclude isIncludeChineseInString:mySearchBar.text]) {
        for (NSString *tempStr in dataArray) {
            NSRange titleResult=[tempStr rangeOfString:mySearchBar.text options:NSCaseInsensitiveSearch];
            if (titleResult.length>0) {
                [searchResults addObject:tempStr];
            }
        }

    }*/

    
    [self p_sendReuqestTableView:self.urlString keyword:searchText];
    
    
    

}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    cell.frame = CGRectMake(-320, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
    [UIView animateWithDuration:0.7 animations:^{
        cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
    } completion:^(BOOL finished) {
        ;
    }];
}



#pragma mark-------------------发起网络请求获取资讯列表-------
//网络请求用于显示在cell上的数据
- (void)p_sendReuqestTableView:(NSString *)urlString keyword:(NSString *)keyword
{
    
    
    NSString * str = [NSString stringWithFormat:@"%@?keyword=%@",urlString,keyword];
    NSString * codeString = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    __block SearchViewController  * searchVC = self;
    [[NetHelper shareInstance]loadingDataWithUrlString:codeString urlExpireInSeconds:30 download:^(NSURLResponse *response, NSData *data, NSError *error) {
        
        if (data != nil && error == nil) {
            
            NSDictionary * sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            self.dataArray = [NSMutableArray array];
            //数据处理
            NSArray * sourceArray = sourceDic[@"yi18"];
            for (NSDictionary * dic in sourceArray) {
                SearchResultModel * searchResult = [[SearchResultModel alloc] init];
                [searchResult setValuesForKeysWithDictionary:dic];
                [searchVC.dataArray addObject:searchResult];
                [searchResult release];
            }
            
            [_searchResults addObjectsFromArray:searchVC.dataArray];
          
            
        }else {
            [KGStatusBar showErrorWithStatus:@"请求网络错误,请检查网络"];
        }
        
        //刷新数据
        [searchVC.searchDisplayController.searchResultsTableView reloadData];
        [searchVC.tableView reloadData];
    }];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
